package com.grouppurchase.controller;

import com.grouppurchase.common.Result;
import com.grouppurchase.entity.Product;
import com.grouppurchase.mapper.ProductMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
@Api(tags = "商品管理", description = "提供商品相关的查询接口")
public class ProductController {

    @Autowired
    private ProductMapper productMapper;
    
    @GetMapping("/list")
    @ApiOperation(value = "获取商品列表", notes = "获取所有上架商品列表，按创建时间倒序排列")
    public Result<List<Product>> getProductList() {
        List<Product> products = productMapper.selectActiveProducts();
        return Result.success(products);
    }

    @GetMapping("/detail/{productId}")
    @ApiOperation(value = "获取商品详情", notes = "根据商品ID获取商品详细信息")
    public Result<Product> getProductDetail(@ApiParam(value = "商品ID", required = true) @PathVariable Long productId) {
        Product product = productMapper.selectById(productId);
        if (product != null) {
            return Result.success(product);
        }
        return Result.error("商品不存在");
    }

    @GetMapping("/category/{categoryId}")
    @ApiOperation(value = "按分类获取商品", notes = "根据商品分类ID获取该分类下的商品列表")
    public Result<List<Product>> getProductsByCategory(@ApiParam(value = "分类ID", required = true) @PathVariable Long categoryId) {
        List<Product> products = productMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Product>()
                .eq(Product::getCategoryId, categoryId)
                .eq(Product::getStatus, 1)
                .orderByDesc(Product::getSortOrder)
                .orderByDesc(Product::getCreatedAt)
        );
        return Result.success(products);
    }
}
